<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { layerList } from '@/utils/api.js'
import * as mars3d from "mars3d";
import "mars3d/dist/mars3d.css";
//引入cesium基础库
import "mars3d-cesium/Build/Cesium/Widgets/widgets.css";
import * as Cesium from "mars3d-cesium";
const emit = defineEmits(['camera-cal', 'calobj'])
import tab from '@/assets/images/tab1.png'
import tab2 from '@/assets/images/tab2.png'
const navList = ref([
    {
        id: '0001x',
        name: "功能区划",
        type: "gnqh",
        sts: true,
    },
    {
        id: '0002x',
        name: "网格",
        type: "wg",
        sts: false,
    }
])

const BaseLayer = ref([]);
let baseType = ref('功能区划');

// 地图变量
let areaId = '';
let maptd = null;
let pointLayer = null;
let yjlayer = null;
let patrolLayer = null;
let yjobj = {};
let WalkObj = {};
let devpoint = {};
let layerObj = {};
const PersonModel = '//data.mars3d.cn/gltf/mars/man/walk.gltf'
// 初始化地图
const maptdInit = () => {
    var mapOptions = {
        scene: {
            //默认视角参数
            center: { "lat": 40.029431, "lng": 116.805358, "alt": 6957.2, "heading": 356, "pitch": -33.8 },
            shadows: false, //是否启用日照阴影
            removeDblClick: true, //是否移除Cesium默认的双击事件

            //以下是Cesium.Viewer所支持的options【控件相关的写在另外的control属性中】
            sceneMode: 3, //3等价于Cesium.SceneMode.SCENE3D,

            //以下是Cesium.Scene对象相关参数
            showSun: true, //是否显示太阳
            showMoon: true, //是否显示月亮
            showSkyBox: true, //是否显示天空盒
            showSkyAtmosphere: true, //是否显示地球大气层外光圈
            fog: true, //是否启用雾化效果
            fxaa: true, //是否启用抗锯齿

            //以下是Cesium.Globe对象相关参数
            globe: {
                depthTestAgainstTerrain: false, //是否启用深度监测
                baseColor: '#546a53', //地球默认背景色
                showGroundAtmosphere: true, //是否在地球上绘制的地面大气
                enableLighting: false //是否显示昼夜区域
            },
            //以下是Cesium.ScreenSpaceCameraController对象相关参数
            cameraController: {
                zoomFactor: 3.0, //鼠标滚轮放大的步长参数
                minimumZoomDistance: 1, //地球放大的最小值（以米为单位）
                maximumZoomDistance: 50000000, //地球缩小的最大值（以米为单位）
                enableRotate: true, //2D和3D视图下，是否允许用户旋转相机
                enableTranslate: true, //2D和哥伦布视图下，是否允许用户平移地图
                enableTilt: true, // 3D和哥伦布视图下，是否允许用户倾斜相机
                enableZoom: true, // 是否允许 用户放大和缩小视图
                enableCollisionDetection: true //是否允许 地形相机的碰撞检测
            }
        },
        control: {
            baseLayerPicker: false, //basemaps底图切换按钮
            homeButton: false, //视角复位按钮
            sceneModePicker: false, //二三维切换按钮
            navigationHelpButton: false, //帮助按钮
            fullscreenButton: false, //全屏按钮  
        },
        terrain: {
            url: 'http://data.mars3d.cn/terrain',
            show: true
        },
        basemaps: [{
            name: '天地图卫星',
            icon: 'img/basemaps/tdt_img.jpg',
            type: 'tdt',
            layer: 'img_d',
            key: ['f24cec70606332017dcd39a4fb60dd11'],
            show: true
        }],
    };
    maptd = new mars3d.Map("mars3dContainer", mapOptions);
    maptd.scene.globe.depthTestAgainstTerrain = true;
    // fly();
    // 创建点位图层
    pointLayer = new mars3d.layer.GraphicLayer({});
    maptd.addLayer(pointLayer);
    // 预警图层
    yjlayer = new mars3d.layer.GraphicLayer();
    maptd.addLayer(yjlayer);
    // 创建巡护图层
    patrolLayer = new mars3d.layer.GraphicLayer({ zIndex: 15, });
    maptd.addLayer(patrolLayer);
};

// 开场动画
const fly = () => {
    maptd.openFlyAnimation({
        duration: 1000,
        // easingFunction: Cesium.EasingFunction.QUINTIC_IN_OUT,
        callback: function () {
            // 动画播放完成后回调
            maptd.setCameraView({ "lat": 31.995112, "lng": 111.406251, "alt": 2074.6, "heading": 100.4, "pitch": -24.9 })
        }
    })
};

//3D视图
const mto3 = () => {
    maptd.scene.morphTo3D(0);
    // maptd.setCameraView({ "lat": 40.49638, "lng": 117.503944, "alt": 1870, "heading": 342.3, "pitch": -12 });
};

//2D视图
const mto2 = () => {
    maptd.scene.morphTo2D(0)
};

const millisecondsToHours = (milliseconds) => {
    var seconds = milliseconds / 1000;
    var hours = seconds / 3600;
    return hours.toFixed(2);
}


// 创建wms
const addwms = (id, data) => {
    if (layerObj.hasOwnProperty(id)) {
        removelayers(id);
    } else {
        layerObj[id] = new mars3d.layer.WmsLayer({
            url: data.layerUrl,
            layers: data.layerName,
            parameters: {
                transparent: true,
                format: "image/png",
                cql_filter: data.cql,
                STYLES: data.styleId
            },
            // opacity: 0.5
        })
        if (maptd != null) {
            maptd.addLayer(layerObj[id]);
        }
    }
}

//单加
const Sigaddwms = (id, data) => {
    layerObj[id] = new mars3d.layer.WmsLayer({
        url: data.layerUrl,
        layers: data.layerName,
        parameters: {
            transparent: true,
            format: "image/png",
            cql_filter: data.cql,
            STYLES: data.styleId
        },
        // opacity: 0.5
    })
    if (maptd != null) {
        maptd.addLayer(layerObj[id]);
    }
}
//单删
const Sigremovelayers = (id, data, callback) => {
    maptd.removeLayer(layerObj[id], true)
    delete layerObj[id];
    callback(id, data)
}

// 删除wms
const removelayers = (id) => {
    maptd.removeLayer(layerObj[id], true)
    delete layerObj[id]
}

//分类点位
const addPoint = (data, icon) => {
    for (let i = 0; i < data.length; i++) {
        const position = [data[i].lon, data[i].lat, data[i].alt];
        let point = new mars3d.graphic.BillboardEntity({
            position: position,
            style: {
                label: {},
                image: icon,
                scale: 2,
                scaleByDistance: false,
                clampToGround: true,
                visibleDepth: true,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                scaleByDistance: new Cesium.NearFarScalar(1000, 1, 5000, 0.5),
            },
            attr: {}
        })
        pointLayer.addGraphic(point)
    }
}

//删除点位
const removepoint = () => {
    maptd.removeLayer(pointLayer, true)
}

// 设备点位
const adddevices = (id, data, icon) => {
    //设备点位图层
    devpoint[id] = new mars3d.layer.GraphicLayer({});
    maptd.addLayer(devpoint[id]);
    for (let i = 0; i < data.length; i++) {
        let p = data[i];
        const position = [p.lon, p.lat, 0];
        let po = new mars3d.graphic.BillboardEntity({
            position: position,
            style: {
                image: icon,
                scale: .5,
                scaleByDistance: true,
                clampToGround: true,
                visibleDepth: true,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                // scaleByDistance: new Cesium.NearFarScalar(1000, 1, 5000, 0.5),
            },
            attr: {}
        })
        devpoint[id].addGraphic(po)
    }
}

// 删除设备点位
const deldevices = (id) => {
    maptd.removeLayer(devpoint[id], true);
    delete devpoint[id];
}

// 创建预警点位
const addwi = (data) => {
    console.log(data);
    yjobj['yj' + data.id] = new mars3d.graphic.CircleEntity({
        position: [data.lon, data.lat, data.alt],
        style: {
            radius: 100,
            height: 50,
            clampToGround: true,
            materialType: mars3d.MaterialType.CircleWave,
            materialOptions: {
                color: '#B8290A',
                count: 3,
                speed: 10,
                gradient: 1
            }

        },
        attr: {}
    })
    yjlayer.addGraphic(yjobj['yj' + data.id])
}
//删除预警点
const delwi = (id) => {
    yjlayer.removeGraphic(yjobj['yj' + id], true)
    delete yjobj['yj' + id]
}

// 巡护人员
const ChangeWalk = (data) => {
    if (typeof (WalkObj[data.imei]) != "undefined") {
        let point = new mars3d.LngLatPoint(data.lon, data.lat, data.alt);
        WalkObj[data.imei].addDynamicPosition(point, 5);
    } else {
        WalkObj[data.imei] = new mars3d.graphic.Route({
            id: data.imei,
            name: data.noticeTitle,
            model: {
                scale: 50,
                url: PersonModel
            },
            label: {
                // 不需要文字时，去掉label配置即可
                text: data.noticeTitle,
                font_size: 16,
                font_family: "楷体",
                color: "rgb(253, 231, 78)",
                outline: true,
                outlineColor: "rgb(249, 60, 60)",
                visibleDepth: false,
                distanceDisplayCondition: true,
                distanceDisplayCondition_far: 50000,
                distanceDisplayCondition_near: 0
            },
            attr: data
        });
        patrolLayer.addGraphic(WalkObj[data.imei]);
        let point = new mars3d.LngLatPoint(data.lon, data.lat, data.alt);
        WalkObj[data.imei].addDynamicPosition(point, 0);
    }
}

const DeleteWalk = (data) => {
    if (typeof (WalkObj[data.imei]) != "undefined") {
        WalkObj[data.imei].remove();
        delete WalkObj[data.imei]
    }
}

const destroyMap = () => {
    if (!maptd) {
        return
    }
    maptd.destroy()
    maptd = null
}

const getlayerList = async () => {
    let res = await layerList(areaId)
    if (res.code == '200') {
        BaseLayer.value = res.data;
        qhbase();
    }
}

const qhbase = () => {
    BaseLayer.value.forEach(e => {
        if (e.name == baseType.value) {
            Sigremovelayers('gnqh001', e, Sigaddwms)
        }
    })

}

onMounted(() => {
    areaId = window.sessionStorage.getItem('areaId');
    maptdInit();
    getlayerList();
});



defineExpose({ mto3, mto2, addwms, removelayers, addPoint, removepoint, adddevices, deldevices, addwi, delwi, ChangeWalk, DeleteWalk });

onUnmounted(() => {
    destroyMap()
})

</script>
<template>
    <div id="mars3dContainer">
        <!--tab切换 B-->
        <div class="qhtab">
            <div v-for="(item, index) in navList" :key="item.id" @click="(baseType = item.name, qhbase())">
                <img :src="baseType == item.name ? tab : tab2" alt="" />
                <span style="margin-left: 0.08rem">{{ item.name }}</span>
            </div>
        </div>
        <!--tab切换 E-->
    </div>
</template>
<style scoped>
#mars3dContainer {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
}
</style>